#ifndef QMLLISTENER_H
#define QMLLISTENER_H

#include <qfilesystemwatcher>
#include <QObject>

class QQuickView;
class QQmlApplicationEngine;
class QmlListenerPrivate;

class QmlListener : public QObject
{
    Q_OBJECT
    Q_DISABLE_COPY(QmlListener)
    Q_DECLARE_PRIVATE(QmlListener)

    QScopedPointer<QmlListenerPrivate> const d_ptr;
public:
    explicit QmlListener(const QString &mainQml = QString(), QObject *parent = nullptr);
    ~QmlListener();

    void setIndexQml(const QString &qmlFile);

    void listen(QQuickView *view);
    void listen(QQmlApplicationEngine *engine);

    void addPaths(const QStringList &paths);
    void addPath(const QString &path);

signals:

public slots:
    void reload(const QString &file);
};

class QmlListenerPrivate
{
    Q_DECLARE_PUBLIC(QmlListener)
    QmlListener *q_ptr;
public:
    QmlListenerPrivate(QmlListener *parent);

    void watching();

    QQuickView *view = nullptr;
    QQmlApplicationEngine *engine = nullptr;
    QFileSystemWatcher *watcher;
    QList<QObject *> qmlObjects;
    QString mainQml;
};

void initQmlListener(const QString& strDirectory)
{
        // scan all qml files
        QDir dir(strDirectory);
        dir.setFilter(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot);
        dir.setSorting(QDir::Name);
    
        QStringList files;
        QDirIterator it(dir, QDirIterator::Subdirectories);
        while (it.hasNext())
        {
            it.next();
            QFileInfo info = it.fileInfo();
            if(info.isFile())
            {
                files << info.filePath();
            }
        }
    
        QmlListener listtener;
        listtener.setIndexQml(strDirectory + "/main.qml");
        listtener.addPaths(files);
        listtener.listen(&engine);
}

#endif // QMLLISTENER_H
